package com.zheng.study.base.dao.impl;

import com.zheng.study.base.dao.MongoBaseDao;
import com.zheng.study.base.entity.MongoEntity;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Dao实现类 - mongodb
 * ============================================================================
 * author : fallenpanda
 * createDate:  2016-07-19 。
 * ============================================================================
 */
@Repository
public class MongoBaseDaoImpl<T extends MongoEntity, PK extends Serializable> implements MongoBaseDao<T, PK> {

	private static final int DEFAULT_SKIP = 0;
	private static final int DEFAULT_LIMIT = 200;

	private Class<T> entityClass;

	public MongoBaseDaoImpl(MongoTemplate mongoTemplate){
		this.mongoTemplate = mongoTemplate;
	}

	/**
	 * spring mongodb　集成操作类　
	 */
	@Resource
	protected MongoTemplate mongoTemplate;

	@SuppressWarnings("unchecked")
	public MongoBaseDaoImpl() {
		this.entityClass = null;
		Class<?> c = getClass();
		Type type = c.getGenericSuperclass();//返回本类的父类,包含泛型参数信息
		if (type instanceof ParameterizedType) {
			Type[] parameterizedType = ((ParameterizedType) type)
					.getActualTypeArguments();//泛型参数的实际类型
			this.entityClass = (Class<T>) parameterizedType[0];//第一个泛型
		}
	}

	protected Class<T> getEntityClass() {
		return entityClass;
	}

	public List<T> find(Query query) {
		return mongoTemplate.find(query, entityClass);
	}

	public T findOne(Query query) {
		return mongoTemplate.findOne(query, entityClass);
	}

	public void update(Query query, Update update) {
		mongoTemplate.findAndModify(query, update, entityClass);
	}

	public T save(T entity) {
		mongoTemplate.insert(entity);
		return entity;
	}

	public T findById(String id) {
		System.out.println(entityClass);
		return mongoTemplate.findById(id, entityClass);
	}

	public T findById(String id, String collectionName) {
		return mongoTemplate.findById(id, entityClass, collectionName);
	}

	public long count(Query query) {
		return mongoTemplate.count(query, entityClass);
	}

}
